package com.github.sbb.sherry.primitives.core;

import com.github.sbb.sherry.primitives.api.RuleListener;
import com.github.sbb.sherry.primitives.api.RulesEngine;
import com.github.sbb.sherry.primitives.api.RulesEngineListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public abstract class AbstractRulesEngine implements RulesEngine {

  List<RuleListener> ruleListeners;
  List<RulesEngineListener> rulesEngineListeners;

  public AbstractRulesEngine() {
    this.ruleListeners = new ArrayList<>();
    this.rulesEngineListeners = new ArrayList<>();
  }

  public AbstractRulesEngine(List<RuleListener> ruleListeners,
      List<RulesEngineListener> rulesEngineListeners) {
    this.ruleListeners = ruleListeners;
    this.rulesEngineListeners = rulesEngineListeners;
  }

  @Override
  public List<RuleListener> getRuleListeners() {
    return Collections.unmodifiableList(ruleListeners);
  }

  @Override
  public List<RulesEngineListener> getRulesEngineListeners() {
    return Collections.unmodifiableList(rulesEngineListeners);
  }

  public void registerRuleListener(RuleListener ruleListener) {
    ruleListeners.add(ruleListener);
    ruleListeners.sort(Comparator.comparing(RuleListener::ordered));
  }

  public void registerRuleListeners(List<RuleListener> ruleListeners) {
    this.ruleListeners.addAll(ruleListeners);
    this.ruleListeners.sort(Comparator.comparing(RuleListener::ordered));
  }

  public void registerRulesEngineListener(RulesEngineListener rulesEngineListener) {
    rulesEngineListeners.add(rulesEngineListener);
    rulesEngineListeners.sort(Comparator.comparing(RulesEngineListener::ordered));
  }

  public void registerRulesEngineListeners(List<RulesEngineListener> rulesEngineListeners) {
    this.rulesEngineListeners.addAll(rulesEngineListeners);
    this.rulesEngineListeners.sort(Comparator.comparing(RulesEngineListener::ordered));
  }
}
